package com.lagou.edu.service.impl;

import com.lagou.edu.config.RabbitConfig;
import com.lagou.edu.entity.Order;
import com.lagou.edu.repository.OrderRepository;
import com.lagou.edu.service.OrderService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.ExecutionException;

/**
 * @author 赵虎
 * @date 2021/4/1 1:19 上午
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderRepository orderRepository;

    @Override
    public boolean addOrder(Order order) throws ExecutionException, InterruptedException {
        order.setId(new Random().nextInt(100));

        CorrelationData correlationData = new CorrelationData();
        rabbitTemplate.convertAndSend(RabbitConfig.ORDER_EXCHANGE_NAME, RabbitConfig.ORDER_ROUTER_NAME, order, correlationData);

        // 同步等待，可以设置为异步回调
        CorrelationData.Confirm confirm = correlationData.getFuture().get();
        // 判断发送的消息是否得到broker的确认
        boolean confirmAck = confirm.isAck();
        if (!confirmAck) {
            return false;
        }
        // 发送延迟等待消息
        rabbitTemplate.convertAndSend(RabbitConfig.ORDER_TTL_EXCHANGE_NAME, RabbitConfig.ORDER_TTL_ROUTER_NAME, order.getId());
        return true;
    }

    @Override
    public boolean payOrder(Integer orderId) {
        int count = orderRepository.updateOrderPaid(orderId);
        return count != 0;
    }
}
